package cn.doitedu.javase.io;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Random;

/**
 * @Author: 深似海
 * @Site: <a href="www.51doit.com">多易教育</a>
 * @QQ: 657270652
 * @Date: 2024/2/2
 * @Desc: 学大数据，上多易教育
 *
 * 生成一个文本文件，内容按之前练习的json模板生成，编码要求为 GBK编码
 * 然后将上一步得到的文件，生成一个拷贝，而且这个拷贝的编码要求是UTF-8
 *
 **/
public class _09_BufferedReader加InputStreamReader综合练习 {
    public static void main(String[] args) throws Exception {
        /**
         * 生成初始GBK编码文件
         */
        String actionLogTemplate = "{\"user_id\":${1},\"event_id\":\"${2}\",\"action_time\":${3}}";
        String[] eventIds = new String[]{"点赞","收藏","添加购物车","视频播放"};
        Random random = new Random();

        // 构造一个基础字节输出流
        FileOutputStream outputStream = new FileOutputStream("e:/m.txt");
        // 包装成writer，指定编码集
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream, "GBK"); // 加了编码
        // 将writer包装成bufferedWriter,可以按行操作
        BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter); // 加了行缓冲

        for(int i=0;i<100;i++){
            // 生成数据
            String user_id = random.nextInt(100)+"";
            String event_id = eventIds[random.nextInt(eventIds.length)];
            String action_time = System.currentTimeMillis()+"";

            // 替换模板
            String replace1 = actionLogTemplate.replace("${1}", user_id);
            String replace2 = replace1.replace("${2}", event_id);
            String replace3 = replace2.replace("${3}", action_time);

            // 写出一行
            bufferedWriter.write(replace3);
            bufferedWriter.newLine();

        }

        bufferedWriter.close();

        /**
         * 复制文件，并转码
         */
        // 1. 构造reader
        BufferedReader br = new BufferedReader(new InputStreamReader(Files.newInputStream(Paths.get("e:/m.txt")), "GBK"));
        // 2. 构造writer
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(Files.newOutputStream(Paths.get("e:/m-2.txt")), StandardCharsets.UTF_8));

        // 3. 循环控制，读一行，写出一行
        String line;
        while( (line = br.readLine())!=null  ){
            bw.write(line);
            bw.newLine();
        }

        br.close();
        bw.close();

    }
}
